var express = require('express');
var router = express.Router();
var path = require('path');
var MonoClient = require('mongodb').MongoClient;
var DB_CONN_STR = "mongodb://localhost:27017/youku";

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/loginAction', function(req, res, next) {
  var email = req.query.email;
  var password = req.query.password;

  MonoClient.connect(DB_CONN_STR,function(err,db){
    if(err){
      return;
    }else{
      var conn = db.collection('Users');
      var data = {email:email,password:password};

      conn.find(data).toArray(function(err,results){
        if(results.length>0){
          res.redirect('/');
        }else{
          res.send('请输入正确的用户名密码');
        }
      })
    }
  })
});


router.post('/registerAction', function(req, res, next) {
  var email = req.body.email;
  var password = req.body.password;

  MonoClient.connect(DB_CONN_STR,function(err,db){
    if(err){
      return;
    }else{
      var conn = db.collection('Users');
      var data = {email:email,password:password};

      conn.insert(data,function(err,results){
        console.log(results);
      })
    }
  })
  res.redirect('/login');
});

module.exports = router;
